package com.jqsoft.launcher.util;

import android.app.AlertDialog.Builder;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;

import com.jqsoft.launcher.activity.JQActivity;
import com.jqsoft.launcher.activity.bean.JQCookie;
import com.jqsoft.launcher.activity.bean.UserLoginInfo;
import com.jqsoft.launcher.common.BphsConstants;
import com.jqsoft.launcher.common.BphsURL;
import com.jqsoft.launcher.common.Constant;

import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.cookie.Cookie;
import org.apache.http.impl.client.AbstractHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 网络应用的工具
 * 
 * @author gujunqi date：2013-12-24
 */
public class NetUtil {
	private static String tag = "NetUtil";

	// http 通讯客户端

	// 检查网络和更新apk应用
	public static boolean isConnectWIFIOr3G(JQActivity ctx) {
		// 判断网络连接是否打开
		ConnectivityManager manager = (ConnectivityManager) ctx
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo netWrokInfo = manager.getActiveNetworkInfo();
		if (netWrokInfo == null) {
			BphsConstants.isNetAvailable = false;
			Log.i("setNetInfo", "------------网络链接失败!-------");
			return BphsConstants.isNetAvailable;
		} // 先检查是否有正常介入到网络
		if (netWrokInfo.isAvailable()) {
			Log.i("getExtraInfo", "网络额外信息:" + netWrokInfo.getExtraInfo());
			Log.i("getState", "网络状态:" + netWrokInfo.getState());
			// String netType = getNetType(netWrokInfo);
			// Log.i(tag, "网络类型:" + netType);
			try {
				// 请求客户端版本信息接口，以验证是否可以链接外网
				String url = BphsURL.getCommonPath("VersionCheck");
				String version = AndroidUtil.getAPKVersion(ctx);
				url = url.replace("@Version", version);
				url = url.replace("@mobileMac", AndroidUtil.getDeviceId(ctx));
				Log.d("MainActivity:---", "Version url:" + url);
				// String updateStatus = MBankXMLParser.queryMessage(url, ctx);
				// if (StringUtils.isBlank(updateStatus)) {
				// BphsConstants.isNetAvailable = false;
				// return Constant.NO_NET;
				// }else{ 解析json数据}
				// loginInfo.isShowedUpdateMessage();设置是否弹出提示更新框
				// 然后设置

				// 当前网络可用
//				BphsConstants.isNetAvailable = true;
//				Log.i(tag, "网络连接正常。。。");
				// 把版本检查信息保存的userLoginInfo中，BphsConstants.appVersionCheckResultBean过一段时间不用，在取值时，会是null
//				UserLoginInfo userLoginInfo = UserLoginInfo.getInstances();
//				userLoginInfo
//						.setUpdateStatus(BphsConstants.appVersionCheckResultBean
//								.getStatus());
//				userLoginInfo
//						.setUpdateMessage(BphsConstants.appVersionCheckResultBean
//								.getMessage());
//				userLoginInfo
//						.setUpdateUrl(BphsConstants.appVersionCheckResultBean
//								.getUrl());

			} catch (Exception e) {
				Log.e(tag, "链接网络异常", e);
				BphsConstants.isNetAvailable = false;
			}
		}
		return BphsConstants.isNetAvailable;
	}

	/**
	 * 1.判断网络连接是否打开<br>
	 *
	 * @return connected if connected,else return error message
	 * */
	public static String checkNet(JQActivity act) {
		ConnectivityManager manager = (ConnectivityManager) act
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo netWrokInfo = manager.getActiveNetworkInfo();
		BphsConstants.isNetAvailable = false;
		if (netWrokInfo == null) {
			Log.i(tag, "------------网络链接失败!-------");
			BphsConstants.isNetAvailable = false;
			return Constant.NO_NET;
		} // 先检查是否有正常介入到网络
		if (!netWrokInfo.isAvailable()) {
			BphsConstants.isNetAvailable = false;
			return Constant.NO_NET;
		} else {
			BphsConstants.isNetAvailable = true;
			return Constant.CONNECTED;
		}
	}

	/** 获取网络类型 */
	public static String getNetType(JQActivity act) {
		ConnectivityManager manager = (ConnectivityManager) act
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo netWrokInfo = manager.getActiveNetworkInfo();
		if (null == netWrokInfo) {
			return "";
		}
		int netType = netWrokInfo.getType();
		// 是区分是手机网络还是wifi。
		if (netType == ConnectivityManager.TYPE_WIFI) {
			BphsConstants.NET_TYPE = "您当前使用的网络为WIFI，可放心使用，不会产生资费！是否继续？";
		} else if (netType == ConnectivityManager.TYPE_MOBILE) {
			BphsConstants.NET_TYPE = "您当前使用的网络为手机网络，将产生资费，是否继续？";
		} else {
			BphsConstants.NET_TYPE = "您当前使用的网络为未知网络，有可能产生资费，是否继续？";
		}

		// String netTypeName = netWrokInfo.getTypeName();
		// Log.i(tag, "网络类型:" + netTypeName);
		// if (null == netTypeName) {
		// return "";
		// }
		// netTypeName = netTypeName.toLowerCase();
		// if (netTypeName.equals("mobile")) {
		// // 中国移动wap接入点
		// if (null != netWrokInfo.getExtraInfo()) {
		// String extraInfo = netWrokInfo.getExtraInfo().toLowerCase();
		// if (extraInfo.equals("cmwap")) {
		// BphsConstants.NET_TYPE = "CMWAP";
		// // BphsConstants.WAP_PROXY_IP = "10.0.0.172";
		// }
		// // 中国联通wap接入点
		// else if (extraInfo.equals("uniwap")) {
		// BphsConstants.NET_TYPE = "UNIWAP";
		// // BphsConstants.WAP_PROXY_IP = "10.0.0.172";
		// }
		// // 中国电信wap接入点
		// else if (extraInfo.equals("ctwap")) {
		// BphsConstants.NET_TYPE = "CTWAP";
		// // BphsConstants.WAP_PROXY_IP = "10.0.0.200";
		// }
		// }
		// } else if (netTypeName.equals("wifi")) {
		// BphsConstants.NET_TYPE = "WIFI";
		// }
		return BphsConstants.NET_TYPE;
	}

	/** 判断网络是否通了,是否能连上服务器 */
	// public static boolean isConnectWIFIOrWAP(JQActivity ctx) {
	// ConnectivityManager manager = (ConnectivityManager) ctx
	// .getSystemService(Context.CONNECTIVITY_SERVICE);
	// BphsConstants.isNetAvailable = false;
	// NetworkInfo netWrokInfo = manager.getActiveNetworkInfo();
	// if (netWrokInfo == null) {
	// Log.i(tag, "------------网络链接失败!-------");
	// return BphsConstants.isNetAvailable;
	// } // 先检查是否有正常介入到网络
	// if (netWrokInfo.isAvailable()) {
	// try {
	// // 请求客户端版本信息接口，以验证是否可以链接外网
	// String url = BphsURL.getCommonPath("currentDateTime").replace(
	// "@mobileMac", AndroidUtil.getDeviceId(ctx));
	// Log.d(tag, "判断是否连接到网络 url:" + url);
	// String currentDateTime = BphsXMLParser.queryMessage(url, ctx);
	// Log.d(tag, "判断是否连接到网络 currentDateTime:" + currentDateTime);
	// if (null != currentDateTime && currentDateTime.length() > 0) {
	// BphsConstants.isNetAvailable = true;
	// Log.i(tag, "网络连接正常。。。");
	// }
	// } catch (Exception e) {
	// Log.e(tag, "链接网络异常", e);
	// }
	// }
	// return BphsConstants.isNetAvailable;
	// }

	/**
	 * 检测网络是否可用
	 */
	public boolean isNetWork(JQActivity activity) {
		boolean newWorkOK = false;
		ConnectivityManager connectManager = (ConnectivityManager) activity
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		if (connectManager.getActiveNetworkInfo() != null) {
			newWorkOK = true;
		}
		return newWorkOK;
	}

	/**
	 * 检测网络是否可用
	 */
	protected boolean checkNetWork(JQActivity activity) {
		boolean newWorkOK = false;
		ConnectivityManager connectManager = (ConnectivityManager) activity
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		if (connectManager.getActiveNetworkInfo() != null) {
			newWorkOK = true;
		}
		// 网络连接未打开，打开设置
		if (!newWorkOK) {
			setNetworkMethod(activity, false);
		}
		return newWorkOK;
	}

	/**
	 * 检测网络是否可用
	 */
	protected boolean checkNetWork(JQActivity activity, boolean isMustNet) {
		boolean newWorkOK = false;
		ConnectivityManager connectManager = (ConnectivityManager) activity
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		if (connectManager.getActiveNetworkInfo() != null) {
			newWorkOK = true;
		}
		// 网络连接未打开，打开设置
		if (!newWorkOK) {
			setNetworkMethod(activity, isMustNet);
		}
		return newWorkOK;
	}

	/**
	 * 打开设置网络界面 不打开网络可以根据isMustNet来关闭界面
	 *
	 * @Description
	 * @param context
	 */
	public static void setNetworkMethod(final JQActivity activity,
			final boolean isMustNet) {
		// 提示对话框
		Builder builder = null;
		if (activity.getParent() != null
				&& activity.getParent().getParent() != null) {
			builder = new Builder(activity.getParent());
		} else {
			builder = new Builder(activity);
		}
		builder.setTitle("网络设置提示")
				.setMessage("网络连接不可用,是否进行设置?")
				.setPositiveButton("设置", new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						Intent intent = null;
						// 判断手机系统的版本 即API大于10 就是3.0或以上版本
						if (android.os.Build.VERSION.SDK_INT > 10) {
							intent = new Intent(
									android.provider.Settings.ACTION_WIRELESS_SETTINGS);
						} else {
							intent = new Intent();
							ComponentName component = new ComponentName(
									"com.android.settings",
									"com.android.settings.WirelessSettings");
							intent.setComponent(component);
							intent.setAction("android.intent.action.VIEW");
						}

						if (activity.getParent() != null
								&& activity.getParent().getParent() != null) {
							activity.getParent().startActivity(intent);
						} else {
							activity.startActivity(intent);
						}

					}
				})
				.setNegativeButton("取消", new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						// 必须网络 关闭
						if (isMustNet) {
							activity.finish();
						}
						dialog.dismiss();
					}
				}).show();
	}

	/**
	 * 根据URL取出cookie,保存起来,在webview中手动的对url设置cookie<br>
	 * 2013-2-23 lkk add
	 *
	 * @param url
	 *            要设置的url
	 * @param domainName
	 *            对每个域名设置cookie
	 * @param marketHy
	 */
	public static void setCookies(String url, String domainName) {
		Log.i(tag, "对这个url设置cookie:" + url + ",domainName:" + domainName);
		HttpPost httpPost = new HttpPost(url);
		httpPost.setHeader("Connection", "keep-alive");
		httpPost.setHeader(
				"User-Agent",
				"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.1 (KHTML, like Gecko) Chrome/14.0.803.0 Safari/535.1");
		try {
			HttpClient httpclient = new DefaultHttpClient();
			httpclient.execute(httpPost);
			UserLoginInfo login_info = UserLoginInfo.getInstances();
			List<Cookie> cookies = ((AbstractHttpClient) httpclient)
					.getCookieStore().getCookies();
			Map<String, List<JQCookie>> cookiesMap = login_info.getCookies();
			List<JQCookie> mbCookies = new ArrayList<JQCookie>();
			if (cookies.isEmpty()) {
				Log.i(tag, url + " Cookie is emtpy---------");
			} else {
				Cookie cookie = null;
				for (int i = 0; i < cookies.size(); i++) {
					cookie = cookies.get(i);
					Log.d(tag, "手动的对url设置cookie Name:" + cookie.getName()
							+ "=value:" + cookie.getValue());
					mbCookies.add(new JQCookie(cookie.getName(), cookie
							.getValue()));
				}
			}
			cookiesMap.put(domainName, mbCookies);
			login_info.setCookies(cookiesMap);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
